//
//  GameObjectItemDelegate.cpp
//  Editor
//
//  Created by Jeppe Nielsen on 11/14/14.
//  Copyright (c) 2014 Jeppe Nielsen. All rights reserved.
//

#include "GameObjectItemDelegate.hpp"
#include <QtWidgets/QtWidgets>
#include "SerializedProperty.hpp"


void GameObjectItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const {
    QStyledItemDelegate::paint(painter, option, index);
}

QSize GameObjectItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                             const QModelIndex &index) const
{
    return QStyledItemDelegate::sizeHint(option, index);
}





QWidget *GameObjectItemDelegate::createEditor(QWidget *parent,
                                    const QStyleOptionViewItem &option,
                                    const QModelIndex &index) const

{
/*
    if (index.data().canConvert<StarRating>()) {
        StarEditor *editor = new StarEditor(parent);
        connect(editor, SIGNAL(editingFinished()),
                this, SLOT(commitAndCloseEditor()));
        return editor;
    } else {
        return QStyledItemDelegate::createEditor(parent, option, index);
    }
    */
    
    ISerializedProperty* property = static_cast<ISerializedProperty*>(index.internalPointer());
    
    if (property->GetEditor()) {
        QWidget* editor = property->GetEditor()->CreateEditor(property, parent);
        return editor;
    }
    
     return QStyledItemDelegate::createEditor(parent, option, index);
}

void GameObjectItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    ISerializedProperty* property = static_cast<ISerializedProperty*>(index.internalPointer());
    
    if (property->GetEditor()) {
        property->GetEditor()->Started(property, editor);
    } else {
        QStyledItemDelegate::setEditorData(editor, index);
    }
}

void GameObjectItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                const QModelIndex &index) const
{
    ISerializedProperty* property = static_cast<ISerializedProperty*>(index.internalPointer());
    if (property->GetEditor()) {
        property->GetEditor()->Finished(property, editor);
    }

    QStyledItemDelegate::setModelData(editor, model, index);
}

void GameObjectItemDelegate::commitAndCloseEditor()
{
    QTextEdit *editor = qobject_cast<QTextEdit *>(sender());
    
    emit closeEditor(editor);
}
